<?php

namespace App\Console\Commands\Mybank;

use App\Kuafu\Mybank\Enum\MybankAccountEnum;
use App\Remote\Mybank\Remote;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Utils;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
use RobRichards\XMLSecLibs\XMLSecurityDSig;
use RobRichards\XMLSecLibs\XMLSecurityKey;

class TestMyBankCommand extends Command
{
    protected $signature   = 'testMyBank';
    protected $isvOrgId    = '';
    protected $appId       = '';
    protected $bkServerUrl = '';
    protected $sbServerUrl = '';
    protected $privatekey;


    // 余额查询 - 模块
    protected $bankCardNo;

    protected $orderNo;
    protected $outMchId;


    protected $batchNo;
    protected $batchDate;

    protected $acquireId = "DEFAULT";

    protected $baseRequestUrl;
    protected $baseFunction;
    protected $merchantNo;

    private static function getPrivateKey($str)
    {
        return "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($str, 64, "\n", true) .
            "\n-----END RSA PRIVATE KEY-----";
    }


    public function chooseEnv(string $env = 'qa')
    {
        if ($env == 'prod') {
//            $this->bkServerUrl = 'https://bkgw.mybank.cn/open/lite/api/common/request.htm';
//            $this->sbServerUrl = 'https://fcopen.mybank.cn/open/api/common/request2.htm';
//            $this->isvOrgId    = '202211000000000001981';
//            $this->appId       = '2023020800001981';
//            $this->merchantNo  = '226801000169831633537'; // 张伟志的店 线上
//
//            $this->bankCardNo = '99030360857300522006';
//
            $privateKey = 'MIIEowIBAAKCAQEAvBhJoQSb8B6DWEA2VFITDvhpCBkuJMws1du0KuVaSFSyrCh8+8v5dLG1Kn2kdkr2LO0ghcbqs8t71mlm3BsVKAVW1aULeHFP46LDXQT1SQKFe/JxqcCUN9ionbzeenUxVimATZI7CE2wIu6tIy5kRsDvjhwWF+t5CdcUZQsKvKdeKks63+KPLkyc7jYQgQFfJ5jHkkyq5SsbGHdU1NrfPs+069YgS0wkN0U95zStbIMbgDkQR61tgQkIyRsrUVkAovDOkGfUsiI0EarNKOqRnZR+0bZGkhAWaalrzyyOmEi4EwNN9XR7/pJhnTNn9ER7bMQkmdYNg+jPjnqbnJjLDwIDAQABAoIBAH2tSL0ChGLLMH1t4h8y+7L7/cnAcVl65tY5x0cGGe3MUdm/78qaPmJfPqpWauXzLktUYW+hOj7JzkO0B1s36UnlT2DOtzxRkcyKeziS0IVo3uGzW4jNuPsbk4ZZpNlzpnRopGawNytUJUUh7qNcIvo3fZiZYZW36xbNE75zw0fK81R/fju+xTvN26hm2A5VjP7y7crqYPOEM6H5HBoGdNFYmo7GeD1NmiXtHMq9jkL2ufzzCbaM3uXcG/LlvpOWjWPY82NaMUKV6Vvl9pw4eMEy9LbEC3Nf4sgwjHYzefu2zt5ZsdP2mblZr6OvYe/L5XTHsOyo4mZmBMja97U2y0kCgYEA3uB5dRjK8gJ2/0XkZSveNXBwLla0CHguAoFU1nFcxotcA8+XtHuIE9NYc+IjkQjJJ6Gw9OOWFu2iPk55RqjA5Up0WCU/q+FV5siuAjLeG5y4pEzvaqnJ0mbXgSeyOczl/u/aC6wGWzLJLdTfV99mBDr0nZooAR3vEyhPOmNEKpUCgYEA2AyBXYJPvN21/a+ZuKG1Ip1//sPUYjMmsOadldrFCRBCFlXaMAqLb1dsmc0R2nVvRHkThhG+aKRlfQRBDz2PlUogObWuWZSIxEe2C3YcDY6IKN8MtVZeU+mLe8I/f+pBQAyw3GOnYEfIJOhXlZ6o0zjFy4yoG7s3fop/0bo8mhMCgYBhlriX5Ts3rIyeSeQvyH2LuKfmImDCNJ0wy6ByJUESToMDyCoNBOoYhDn+w83++3HYwJvTHrPhZjvcPFAt+EY+H9PBpM20XP5YBxbqL4vBW2YdyvIqKh4M2qsSCmenl2g9sJgw9Cn0VNByGPuSZmctAwOI3q8Vjh3YrZXDYyO94QKBgGYvO/yTRs2Ie6xaIrW93iNaJRDFZK1xjgo7eStIhsrroqZXwtPYGOz3h4kTAi+2PYNAVOijedCaeNnxaiggMMomfiltceIyq6FSXZr8KPaMhH/4R1V5XTIJEwzc6hXBIU1+8yO6Co8yREqYjdxZZ3ZHst28UEKVgQDb1urGUCV7AoGBAL1Z4w3agcdE5nab2zm7qT/E7Grqn5IIGwUSNlcPh87f+Yb3rTnug7d5UrglemGAglT5g8KVkg2Gj5a82zfFj1lr7+1uxj8rsI4eYHLybFVLtvn2nfLb5ptk1dlEfxT8+w+UktDAiWwKcUSbWbnwAG+VWpgDyI0uSXUK33COlIkX';
        } else {
            $this->bkServerUrl = 'http://bkgwdev.dl.alipaydev.com/open/lite/api/common/request.htm';
            $this->sbServerUrl = 'https://fcsupergw.mybank.dl.alipaydev.com/open/api/common/request2.htm';
            $this->isvOrgId    = '202211000000000001902';
            $this->appId       = '2022121300001902';
            $this->merchantNo  = '226801000000854288982';
            $this->bankCardNo  = '99030270636000109002';

            $privateKey = 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC+DjjKuBYNScrhp7/+yf/vqsZbyWAMuvLZ76rv9wLA3XTCY1Cb3xxm7xvux/OzhzDlQdURRrEhjjsVdP9Bx0Ig5yfGyDec/4Z50dcRgqsu17QU/m2WXHEwFd4yBAGomWXzy/q7+8JJ9YoTraSDfKhfV3qWx7/vBzqk0QNzZ3AgFwSMiP5Azz8K2GhkHWxbVLlji9+/oRL5yj13a8P9bbtIrdUB/PZ+Fk3klxhBL9Vxii0YmX96nwVuJgkmgyiRCwmLhIQBFdL7H63cNgUi9UoCsFC6lV4ErEcHCUFsLqggukKPmTlr4KSnFvf9bZoIYC9I7XBWcM+KDGTSdxeGpXbvAgMBAAECggEABIJr4It7oncUxEPpr071rqcbq8PcbpDlADzKjoUK4K6gfZhDql8h2mNkA0dlReY4R8hHGPDXdRdd2YV8JQBoVkWF0RahEy2Q8EUFWFoEW8ksca8TxJSO7vgl3IPx0iFJpP47BcjUdFLKIutk0uXbTN/Tfc5hhHdkcdKvxUY4B9rZYSNI5+YdIGjJj/nBWNGBndIqKnLfs2AhpCqPkADC3xo73fxiM/77TPB7RiaFeK9jk80kLAwaZeOKArCIY7YSpnyhqvPi4kO9vxTeGGHONhN+mfAsMG94AY83vZ6qhUiZZuofslbUt7beOw2PTmzGi8jXDI8k6WVHKqNnwYt/+QKBgQD/fT8sG3oJyRpvfhc/gPM+ovYGL3MH+6B3Gtq32K+ZyAmtoHnfLFkaa1bOLUEklvr2xViFTU4NlUyEWNE1jGW1JFC9AhU3JUnVKmiG/BSURH8neYsNUQ/yKOmjRyTvQmELp2Qb7h46ZWM6kWOzrJtiXMvkoAjWwgO/4YOxEazJdQKBgQC+b3zZW/yh/cOTCAzfN8AR/luSq9TJ7D8CZxHVOpXRL3YP950SUWEfuyOby4ddhFDwU3b6+BhtOtClMrBKO2Q9wbPVjVD5plGlhhMaLiNJmbFL63hEazrMOE3UVbOY8EYBJyyeUguqiYyRJkUbiVubRsdbFLUbGai8qWg5BvTOUwKBgEFOUoeDvn4h2ZAGOwsQexzXquuJ1W2E9E99ncrAqKI2b8Lh8kUJoP0P0vCAwNYJgbzyVN4+FGWEdDqgOVnmuVjEH58wmRuvfF/wpydZ6Ci+GYKNnu2Yeur7aj1CQj6mSQghkYVSKIfkwqiF4WZcCJvr/HJENf4vOaYijvcD/ZbBAoGBAKoZFyFnIq7m5cvtAuJW/76SveSyiuyZkmZo/erB25PvmrsEZ043VlNrapD8KLsFNu6S/tGIzPiz8i28qu6DQjRPUnxLL6ruPjtlGKbn0ykomM7BUrl6Nhi3qf0hV7wh0cWx4g7AJh97oQz9a/j+pc56WBMo2eOM9cUeZDOb3Qp1AoGAQwB8ndcxkt4UCfC+87Rpy5yrxVuaVKDZfTIy4qpuLrHRqCIHvAl41EnJTE8MPIemXhdTmPeLmGWe7KjGDo0F0GPRqBMVKrLrCnM52FUx/Wp5P2h8ZVXvm7TR5/b3jhCb7qC0gjey+HunyEn78H9Vxty4XzcSlF0zu8uVUSgwIJ8=';
        }
//        $this->chooseSFTP($env);
        $this->privatekey = self::getPrivateKey($privateKey);
    }


    public function chooseSFTP($env)
    {
        if ($env == 'prod') {
//            config('');8
        } else {

        }
    }


    // 创建订单
    public function createOrder()
    {
        $this->baseRequestUrl = $this->sbServerUrl;
        $this->baseFunction   = 'ant.mybank.bkcloudfunds.unifiedorder.create';

        $xml = self::requestData([
              'IsvOrgId'             => $this->isvOrgId,
              'OrderType'            => '06',// 订单类型编号
              'OutTradeNo'           => time(),// 外部订单请求流水号
              'TotalAmount'          => 1,// 订单总金额
              'Currency'             => 'CNY',// 币种
              'PayeeId'              =>  '226801000000917273821',// 收方ID 若Type为 MERCHANT，ID为商户号
              'PayeeType'            => 'MERCHANT',// 收方类型  MERCHANT
              'PayerId'              => '',// 付方ID  若Type为 MERCHANT，ID为商户号
              'PayerType'            => 'MEMBER',// 付方类型  MERCHANT
              'Body'                 => '测试商品',// 商品描述。该信息在客户端明细中展示。
              'GoodsTag'             => '',// 商品标记。
              'GoodsDetail'          => '',// 商品详情列表
              'SubOrderList'         => '',// 合并支付时，明细单列表
              'ExtInfo'              => '',// 扩展信息 商品信息 单件 数量
              'Memo'                 => '',// 备注（可填写订单描述信息）
              'IsPayToBalanceFreeze' => 'N',// 是否入账到可用子户冻结成分 Y：入金到收方可用冻结 N（或其他非Y值）：入金到收方可用解冻 不传默认N的逻辑
          ]);

        return $this->baseRequest($xml);
    }

    // 统一支付订单查询接口
    public function queryOrder()
    {
        $this->baseRequestUrl = $this->sbServerUrl;
        $this->baseFunction   = 'ant.mybank.bkcloudfunds.unifiedorder.query';

        $xml = self::requestData( [
            'IsvOrgId'             => $this->isvOrgId,
            'OrderNo'            => '202312822512332882',// 网商订单号
            'OutTradeNo'           => '1703499192',// 外部订单请求流水号
        ]);

        return $this->baseRequest($xml);
    }

    // 支付退回申请接口
    public function refundApplyOrder()
    {
        $this->baseRequestUrl = $this->sbServerUrl;
        $this->baseFunction   = 'ant.mybank.bkcloudfunds.refund.apply';

        $payeeInfo = MybankAccountEnum::getKfosOrderAccount();

        $xml = self::requestData([
            'IsvOrgId'        => $this->isvOrgId,
            'ParticipantType' => $payeeInfo['payeeType'],// 退款付方类型，即原支付单收方  商户(MERCHANT)、 平台(PLATFORM)
            'ParticipantId'   => $payeeInfo['payeeId'],// 退款付方id，即原支付单收方 如果是商户，则填入merchantId, 如果是平台，则填入isvOrgId
            'RelateOrderNo'   => '202312822512332882',// 关联网商订单号
            'RelateTransNo'   => '',// 关联网商支付流水号 支付流水号  1）如果大额来账创建订单类型为单次订单，可不填 2）如果大额来账创建订单类型为订单累计，则必填
            'OutRefundNo'     => '1703499892',// 退款外部交易号。由合作方生成，同笔退款交易，交易状态未明需要重试时，使用同一个交易号。
            'RefundAmount'    => 1,// 订单退款金额。向渠道退款金额。
            'Currency'        => 'CNY',// 币种
            'RefundReason'    => '测试退款',// 退款原因
            'ExtInfo'         => '',// 扩展信息,Map的json序列化后Base64
            'Memo'            => '',// 备注
        ]);

        return $this->baseRequest($xml);
    }

    // 支付退回查询接口
    public function refundQueryOrder()
    {
        $this->baseRequestUrl = $this->sbServerUrl;
        $this->baseFunction   = 'ant.mybank.bkcloudfunds.refund.query';

        $payeeInfo = MybankAccountEnum::getKfosOrderAccount();

        $xml = self::requestData( [
            'IsvOrgId'        => $this->isvOrgId,
            'RelateOrderNo'   => '202312822512332882', // 关联网商订单号
            'ParticipantType' => $payeeInfo['payeeType'], // 退款参与方类型 商户(MERCHANT)、 平台(PLATFORM)、子户汇入（SUBACCOUNT）
            'ParticipantId'   => $payeeInfo['payeeId'], // 退款参与方id 如果是商户，则填入merchantId, 如果是平台，则填入isvOrgId 如果是子户汇入，则填入汇入子户外标
            'OutRefundNo'     => '1703499892', // 退款外部交易号
            'RefundOrderNo'   => '2023122510152061066106820012659691', // 网商退款订单号
        ]);

        return $this->baseRequest($xml);
    }

    // 订单关闭接口
    public function closeOrder($outTradeNo, $orderNo)
    {
        $this->baseRequestUrl = $this->sbServerUrl;
        $this->baseFunction   = 'ant.mybank.bkcloudfunds.vostro.closeOrder';

        $payeeInfo = MybankAccountEnum::getKfosOrderAccount();

        $xml = self::requestData([
            'IsvOrgId'   => Remote::getIsvOrgId(),
            'PayeeType'  => $payeeInfo['payeeType'],// 参与方类型 商户(MERCHANT)、平台(PLATFORM)
            'PayeeId'    => $payeeInfo['payeeId'],// 作为收款方账号。 1. 如果收款方是平台，那么这个字段的值和 IsvOrgId 相同2. 如果收款方是商户，那么这个字段是商户号（merchantId）
            'OutTradeNo' => $outTradeNo,// 原外部订单请求流水号
            'OrderNo'    => $orderNo,// 原网商订单号
        ]);

        return $this->baseRequest($xml);
    }

    public function handle()
    {
        $this->chooseEnv('qa');

        $res = $this->closeOrder('202401051132251418659860','202401380554310481');dd($res);
        //        $res = $this->refundApplyOrder();dd($res);
//        $res = $this->refundQueryOrder();dd($res);
//        $res = $this->createOrder();dd($res);
//        $res=$this->queryOrder();dd($res);

        $orderNo     = '202312822512332882';//$res['response']['body']['OrderNo'];
//        $orderPayUrl = base64_decode($res['response']['body']['OrderPayUrl']);
        var_dump($orderNo);

        $uid = '2088502337851303';// 支付宝UID

        // 线下免入驻支付链接用这个，替换里面的参数
        $ali = "alipays://platformapi/startapp?appId=2021002115660005&nbupdate=syncforce&query=order%3D{$orderNo}%26isv%3D{$this->isvOrgId}%26app%3Dbkclfs%26t%3DPAY%26uid%3D{$uid}";

        dd( $ali);
//        $this->orderNo = '2023062711150800120000000000000095962293';

//        $this->outMchId = '1671439755';
//        $this->merchantNo = '226801000000777694617';  // 个人
//        $this->merchantNo = '226801000000761783643'; // 个体工商户
//        $this->merchantNo = '226801000000854288982';

//        $uid = '2088502337851361';
//        $merchantNo  = '226801000000761783643';
//        $aliyunLogin = "alipays://platformapi/startapp?appId=2021002115660005&nbupdate=syncforce&query=mchId%3D{$merchantNo}%26isv%3D{$this->isvOrgId}%26app%3Dbkclfs%26t%3DLOGIN%26uid%3D{$uid}";
//        dd($aliyunLogin);

        $this->handlerPreRegister();
//        $this->handleBatch();
//        $this->handleArrangement();
////        $this->handleBalanceQuery();
////
//        $dealFundsBillPayResult = $this->dealFundsBillPay();
//        dd($dealFundsBillPayResult);

//
//        $unfreezeApplyResult = $this->unfreezeApply();
//        dd($unfreezeApplyResult);
//        die;
//        $unfreezeApplyQueryResult = $this->unfreezeApplyQuery();
//        dd($unfreezeApplyQueryResult);

//        $batchBillQueryResult = $this->batchBillQuery();
//        dd($batchBillQueryResult);

    }

    public function dealFundsBillPay()
    {
        $this->baseRequestUrl = $this->sbServerUrl;
        $this->baseFunction   = 'ant.mybank.bkcloudfunds.bill.pay';

        $xml = self::requestData([
            'IsvOrgId'        => $this->isvOrgId,
            'PayeeMerchantId' => $this->merchantNo,
            'OutTradeNo'      => time(),
            'TotalAmount'     => '1921',
            'Currency'        => 'CNY',
            'TradeType'       => 'SINGLE_PAY',
            'ChannelType'     => 'WXPAY',
            'Body'            => '夸父炸串-炸串',
        ]);

        return $this->baseRequest($xml);
    }

    public function handleBalanceQuery()
    {
        $balanceQueryResult                                    = $this->balanceQuery();
        $balanceQueryResult['response']['body']['BalanceInfo'] = json_decode(base64_decode($balanceQueryResult['response']['body']['BalanceInfo']),
            1);
        $balanceQueryResult['response']['body']['ExtInfo']     = json_decode(base64_decode($balanceQueryResult['response']['body']['ExtInfo']),
            1);
        dd($balanceQueryResult);
//
//
//        $accountBalanceQueryResult = $this->accountBalanceQuery();
//        dd($accountBalanceQueryResult);
        $balanceUnfreezeQuery = $this->balanceUnfreezeQuery();
        dd($balanceUnfreezeQuery);
    }


    /**
     * 余额查询
     *
     * @return mixed
     */
    public function balanceQuery()
    {
        $this->baseRequestUrl = $this->sbServerUrl;
        $this->baseFunction   = 'ant.mybank.bkcloudfunds.merchant.scene.balance.query';

        $xml = self::requestData([
            'IsvOrgId'   => $this->isvOrgId,
            'MerchantId' => $this->merchantNo,
        ]);

        return $this->baseRequest($xml);
    }
// 226801000000772286614

    /**
     * 子户外标查询余额查询
     *
     * @return mixed
     */
    public function accountBalanceQuery()
    {
        $this->baseRequestUrl = $this->sbServerUrl;
        $this->baseFunction   = 'ant.mybank.bkcloudfunds.account.balance.query';

        $xml = self::requestData([
            'IsvOrgId'    => $this->isvOrgId,
            'BankCardNo'  => $this->bankCardNo,
            'AccountType' => '01',
        ]);

        return $this->baseRequest($xml);
    }

    /**
     * 商户余额解冻结果查询接口
     */
    public function balanceUnfreezeQuery()
    {
        $this->baseRequestUrl = $this->bkServerUrl;
        $this->baseFunction   = 'ant.mybank.bkcloudfunds.merchant.balance.unfreeze.query';

        $xml = self::requestData([
            'IsvOrgId'   => $this->isvOrgId,
            'OutTradeNo' => '247834380544772972', // 请求唯一单号
            'OperateNo'  => '2023062810152061666166030086753278', // 网商操作号
        ]);

        return $this->baseRequest($xml);
    }

    /**
     * 商户余额解冻接口
     */
    public function unfreezeApply()
    {
        $this->baseRequestUrl = $this->bkServerUrl;
        $this->baseFunction   = 'ant.mybank.bkcloudfunds.merchant.account.unfreeze.apply';

        $xml = self::requestData([
            'IsvOrgId'    => $this->isvOrgId,
            'MerchantId'  => $this->merchantNo,
            'OutTradeNo'  => time() . time(),
            'AccountType' => 'BALANCE',
            'Amount'      => '98',
            'Currency'    => 'CNY'
        ]);

        return $this->baseRequest($xml);
    }

    /**
     * 商户余额解冻接口
     */
    public function unfreezeApplyQuery()
    {
        $this->baseRequestUrl = $this->bkServerUrl;
        $this->baseFunction   = 'ant.mybank.bkcloudfunds.merchant.balance.unfreeze.query';

        $xml = self::requestData([
            'IsvOrgId'   => $this->isvOrgId,
            'OperateNo'  => '2023080710152061666166620017323761',
            'OutTradeNo' => '16913810661691381066'
        ]);

        return $this->baseRequest($xml);
    }

    public function handleArrangement()
    {
        $withholdApplyResult = $this->orderWithholdApply();
        dd($withholdApplyResult);

//        $infoQueryResult = $this->arrangementInfoQuery();
//        dd($infoQueryResult);
//
//        $arrangementAudit = $this->arrangementAudit();
//        dd($arrangementAudit);

//


        $orderWithholdQueryResult = $this->orderWithholdQuery();
        dd($orderWithholdQueryResult);

    }

    /**
     * 协议代扣授权状态查询接口
     *
     * @return mixed
     */
    public function arrangementInfoQuery()
    {
        $this->baseRequestUrl = $this->bkServerUrl;
        $this->baseFunction   = 'ant.mybank.merchantprod.merchant.arrangement.info.query';

        $xml = self::requestData([
            'IsvOrgId'        => $this->isvOrgId,
            'MerchantId'      => $this->merchantNo,
            'ArrangementType' => 'SUB_ACCOUNT_WITHHOLD'
        ]);

        return $this->baseRequest($xml);
    }

    /**
     * 解约申请审核确认接口
     *
     * @return mixed
     */
    public function arrangementAudit()
    {
        $this->baseRequestUrl = $this->bkServerUrl;
        $this->baseFunction   = 'ant.mybank.merchantprod.merchant.arrangement.audit';

        $xml = self::requestData([
            'IsvOrgId'      => $this->isvOrgId,
            'MerchantId'    => $this->merchantNo,
            'AuditResult'   => 'REJECT', // AGREE -同意 REJECT-拒绝
            'ArrangementNo' => '2023080401034002000883760624' // 合约号
        ]);

        return $this->baseRequest($xml);
    }

    /**
     * 协议代扣处理
     */
    public function orderWithholdApply()
    {
        //"IsvOrgId" => "202211000000000001902"
        //      "OutTradeNo" => "167160757016716075701671607570"
        //      "OrderNo" => "202212272110918603"
        //      "OperateNo" => "2022122110152061656165270016593006"

        $this->baseRequestUrl = $this->bkServerUrl;
        $this->baseFunction   = 'ant.mybank.bkcloudfunds.order.withhold.apply';

        $xml = self::requestData([
            'IsvOrgId'        => $this->isvOrgId,
            'OutTradeNo'      => time() . time() . time(),             // 代扣业务订单号
            'Scene'           => 'PROTOCOL_WITHHOLD_SUPPORT_FREEZE',
            // 业务场景：品牌协议代扣场景：PROTOCOL_WITHHOLD 品牌协议代扣支持冻结场景： PROTOCOL_WITHHOLD_SUPPORT_FREEZE
            'TotalAmount'     => '100', // 交易金额（分）
            'FreezeAmount'    => '100', // 冻结部分出金（分）
            'AvailableAmount' => '0', // 可用部分金额（分）
            'Currency'        => 'CNY', // 币种
            'PayerId'         => $this->merchantNo, // 付款方商户号
            'PayerType'       => 'MERCHANT', // 付款方类型：MERCHANT
            'PayeeId'         => $this->isvOrgId, // 收款方ID
            'PayeeType'       => 'PLATFORM',// 收款方类型 MERCHANT / PLATFORM
        ]);
        return $this->baseRequest($xml);
    }

    /**
     * 协议授权代扣通知结果
     */
    public function orderWithholdResultNotify()
    {
        $this->baseRequestUrl = $this->bkServerUrl;
        $this->baseFunction   = 'ant.mybank.bkcloudfunds.protocol.withhold.result.notify';

        $xml = self::requestData([

        ]);

        return $this->baseRequest($xml);
    }

    /**
     * 协议授权代扣查询结果
     */
    public function orderWithholdQuery()
    {
        $this->baseRequestUrl = $this->bkServerUrl;
        $this->baseFunction   = 'ant.mybank.bkcloudfunds.protocol.withhold.query';

        $xml = self::requestData([
            'IsvOrgId'   => $this->isvOrgId,
            'OperateNo'  => '2023080710152061656165270018489611',
            'OutTradeNo' => '169138035716913803571691380357'
        ]);

        return $this->baseRequest($xml);
    }

    public function handleBatch()
    {
        $this->batchDate = date('Ymd');
        $this->batchNo   = $this->batchDate . '_2';

//        $batchFileUploadResult = $this->batchFileUpload();
//        dd($batchFileUploadResult);
//        $batchQueryResult = $this->batchCreate();
//        dd($batchQueryResult);
//
        $this->batchINstanceId = "BATCH_CREATE_ORDER_STMT_AVAILABLE_FREEZE" . $this->isvOrgId . "0000" . $this->batchNo;

        // 先上传文件,再处理批次
        $batchQueryResult = $this->batchQuery();
        dd($batchQueryResult);
    }

    /**
     * 来账明细查询 测试环境 查不到
     */
    public function batchBillQuery()
    {
        $this->baseRequestUrl = $this->bkServerUrl;
        $this->baseFunction   = 'ant.mybank.bkcloudfunds.vostro.batchquery';

        $xml = self::requestData([
            'IsvOrgId'     => $this->isvOrgId,
            'VostroCardNo' => $this->bankCardNo,
            'StartTime'    => date('Ymd', strtotime('-7 days')),
            'EndTime'      => date('Ymd'),
        ]);

        dd($this->baseRequest($xml));
        return $this->baseRequest($xml);

    }

    public function batchFileUpload()
    {
        $filePath       = $this->isvOrgId . '/' . $this->acquireId . '/' . $this->batchNo . '/';
        $detailFileName = 'merchant_trade_detail_' . $this->batchNo . '.txt';
        $finishFileName = 'finish_' . $this->batchNo . '.txt';

        //交易明细文件/upload/${isvOrgId}/${acquireId}/${batchNo}/merchant_trade_detail_${batchNo}.txt
        //明细标档文件：/upload/${isvOrgId}/${acquireId}/${batchNo}/finish_${batchNo}.txt
        $batchNo   = $this->batchNo;
        $batchDate = $this->batchDate;

        $detailContent = <<<STR
渠道类型,交易类型,批次号,对账日,网商订单号,isv支付单号,渠道支付单号,isv退款单号,渠道退款单号,交易总金额,实际金额,渠道手续费,币种,用户标识,商户号,交易状态,备注,创单时间,交易时间,收单机构编号
STR;

        $str = "";
        for ($i = 0; $i < 1; $i++) {
            $randomNo = random_int(100000000000000, 99999999999999999);
            $arr      = [
                "ALLINPAY", // 渠道类型,
                "SINGLE_PAY", // 交易类型,
                $batchNo, // 批次号,
                $batchDate, // 对账日,
                '', // 网商订单号,
                $randomNo, // isv支付单号,
                $randomNo, // 渠道支付单号,
                '', // isv退款单号,
                '', // 渠道退款单号,
                '1', // 交易总金额
                '1', // 实际金额,
                '0', // 渠道手续费,
                '156',// 币种,
                '',// 用户标识,
                $this->merchantNo,// 商户号,
                'SUCCESS',// 交易状态,
                '',// 备注,
                date('YmdHis'),// 创单时间,
                date('YmdHis'),// 交易时间,
                $this->acquireId,// 收单机构编号
            ];
            $str      .= implode(',', $arr) . PHP_EOL;
        }

        $detailContent      .= PHP_EOL . $str;
        $detailUploadStatus = Storage::disk('mybank-sftp')->put($filePath . $detailFileName, $detailContent);
        $finishUploadStatus = Storage::disk('mybank-sftp')->put($filePath . $finishFileName, "");

        return true;
    }

    public function baseRequest($xml)
    {
        $client  = new Client(['verify' => false]);
        $headers = [
            'Content-Type' => 'application/xml',
        ];

        $request = new Request('POST', $this->baseRequestUrl, $headers, $xml);
        $res     = $client->sendAsync($request)->wait();

        $result = simplexml_load_string($res->getBody());

        $resultJson = json_decode(json_encode($result), 1);
        unset($resultJson['Signature']);
        return $resultJson;
    }

    /**
     * 创建批次接口
     */
    public function batchCreate()
    {
        $this->baseRequestUrl = $this->bkServerUrl;
        $this->baseFunction   = 'ant.mybank.bkcloudbatch.batch.create';

        $xml = self::requestData([
            'IsvOrgId'       => $this->isvOrgId,
            'BatchNo'        => $this->batchNo,
            'AcquireId'      => 'DEFAULT',
            //BILL_STMT_AVAILABLE_SHARE -- ISV收单，结算至余额(未提前创单)
            //BATCH_CREATE_ORDER_STMT_AVAILABLE_FREEZE -- ISV收单，结算至余额并冻结(未提前创单)
            //STMT_AVAILABLE_SUM_SHARE -- ISV收单，结算至余额并分账（汇总分账）
            'BatchType'      => 'BATCH_CREATE_ORDER_STMT_AVAILABLE_FREEZE',
            'FileUploadType' => 'SFTP'
        ]);

        return $this->baseRequest($xml);
    }

    /**
     * 创建批次接口
     */
    public function batchQuery()
    {
        $this->baseRequestUrl = $this->bkServerUrl;
        $this->baseFunction   = 'ant.mybank.bkcloudbatch.batch.query';

        $xml = self::requestData([
            'IsvOrgId'        => $this->isvOrgId,
            'BatchNo'         => $this->batchNo,
            'BatchInstanceId' => $this->batchINstanceId,
            'AcquireId'       => 'DEFAULT'
        ]);

        return $this->baseRequest($xml);
    }

    public function requestData(array $body)
    {
        $xml = self::baseRequestData($body, $this->baseFunction);

        // XML 加密方式
        //  创建一个XML文档并设置XML版本和编码。。
        $dom = new \DomDocument();

        $dom->loadXML($xml);

        $objDSig = new XMLSecurityDSig();
        // Use the c14n exclusive canonicalization
        $objDSig->setCanonicalMethod(XMLSecurityDSig::C14N);
        // Sign using SHA-256
        $objDSig->addReference(
            $dom,
            XMLSecurityDSig::SHA1,
            [
                'http://www.w3.org/2000/09/xmldsig#enveloped-signature'
            ],
            [
                'force_uri' => true
            ]
        );
        // Create a new (private) Security key
        $objKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA256, array('type' => 'private'));

        $objKey->loadKey($this->privatekey);

        $objDSig->sign($objKey);

        $objDSig->appendSignature($dom->documentElement);

        return $dom->saveXML();
    }

    public function baseRequestData(array $body, string $function)
    {

        $head = [
            'Version'      => '1.0.0',
            // Appid 和 AppId 对应不同接口, 都要写上
            'Appid'        => $this->appId,
            'AppId'        => $this->appId,
            'Function'     => $function,
            'ReqTime'      => date('YmdHis'),
            'ReqMsgId'     => vsprintf("%s-%s-%s", [date('YmdHis'), random_int(100000, 999999), md5(date('YmdHis'))]),
            'InputCharset' => 'UTF-8'
        ];
        $head = array_filter($head, function ($item) {
            return isset($item);
        });
        $body = array_filter($body, function ($item) {
            return isset($item);
        });
        ksort($head);
        ksort($body);

        $headXml = self::arr2xml($head, false);
        $body    = self::arr2xml($body, false);

        $xmlTemplate = <<<TEMPLATE
<?xml version="1.0" encoding="utf-8"?>
<document>
<request>
<head>{$headXml}</head>
<body>{$body}</body>
</request>
</document>
TEMPLATE;

        return $xmlTemplate;
    }


    public function arr2xml($data, $root = true)
    {
        $str = "";
        if ($root) {
            $str .= "<xml>";
        }
        foreach ($data as $key => $val) {
            //去掉key中的下标[]
            $key = preg_replace('/\[\d*\]/', '', $key);
            if (is_array($val)) {
                $child = self::arr2xml($val, false);
                $str   .= "<$key>$child</$key>";
            } else {
//                $str .= "<$key><![CDATA[$val]]></$key>";
                $str .= "<$key>$val</$key>";
            }
        }
        if ($root) {
            $str .= "</xml>";
        }
        return $str;
    }


    /******* - 查询 - ********/

    public function handlerPreRegister()
    {

        //        // 1.1 商家预注册
//        $preRegisterResult = $this->preRegister01();
//        $preRegisterResult = $this->preRegister01_2();
//        $uid = '2088502337851303';
//        dd($preRegisterResult);
////
////        // 1.2 个体工商户 03: 企业商户
//        $preRegisterResult = $this->preRegister02();
//        $uid               = '2088502337851361';
//        dump($preRegisterResult['response']['body']);
//
//        // 1.3 企业商户
//        $uid = '2088502450683119';
////
//        $preRegisterResult = $this->preRegister03();
////        dd($preRegisterResult['response']['body']);
//        $this->orderNo = '2023120711150800120000000000000000856974';
//        // 2. 商户预入驻结果查询接口
////        $registerQueryResult = $this->registerQuery();
////        dd($registerQueryResult);
//
//        $this->outMchId = '1701934363';
//        //        // 3. 生成二维码
//        //        // QA 二维码
//        $qrCode = "alipays://platformapi/startapp?appId=2021002115660005&nbupdate=syncforce&query=outMchId%3D{$this->outMchId}%26isv%3D{$this->isvOrgId}%26app%3Dbkclfs%26t%3DREGISTER%26uid%3D{$uid}";
//        dd($qrCode);

//        // 正式二维码
////        $zsqrCode = "alipays://platformapi/startapp?appId=2021001187624111&nbupdate=syncforce&query=outMchId%3D{outMchId}%26isv%3D{ISV_ORG_ID}%26app%3Dbkclfs%26t%3DREGISTER";
//
//        // 登录测试环境 二维码
//        $qrCode = "alipays://platformapi/startapp?appId=2021002115660005&nbupdate=syncforce&query=mchId%3D{$this->merchantNo}%26isv%3D{$this->isvOrgId}%26app%3Dbkclfs%26t%3DLOGIN%26uid%3D{$uid}";
//        dd($qrCode);


        // 4. 激活结果查询接口
//        $this->outMchId      = '1701934363';
//        $appletRegisterRuery = $this->appletRegisterRuery();
//        dd($appletRegisterRuery);

        // 5. 图片上传
//        $this->outTradeNo = '1687881600';
//        $uploadFileResult = $this->uploadFile();
//        dd($uploadFileResult);

        // 小程序入驻商户信息查询接口

        $merchantQueryResult = $this->merchantprodMerchQuery();
        dd($merchantQueryResult);
//
//        // 黎里镇南京路 369 号 3 幢 121
//        $merchantUpdateResult = $this->merchUpdateMerchant();
//        dd($merchantUpdateResult);
    }

    /**
     * @return mixed 01自然人 激活
     */
    public function preRegister01()
    {
        $this->baseRequestUrl = $this->bkServerUrl;
//        $this->baseRequestUrl = 'https://bkgw.mybank.cn/open/lite/api/common/request.htm';

        $this->baseFunction = 'ant.mybank.bkmerchantprod.merch.applet.pre.register';

        $xml = self::requestData([
            'IsvOrgId'       => $this->isvOrgId,
            'OutTradeNo'     => time(),
            'OutMerchantId'  => '001' . time(), // 商户号
            'MerchantType'   => '01', //商户类型。可选值：01：自然人02: 个体工商户03: 企业商户
//            'MerchantName'   => '夸父炸串测试商户',
            'MerchantName'   => $contactName = '枪鸯勿',
            'DealType'       => '01', // 商户经营类型。可选值：01:实体特约商户02:网络特约商户03:实体兼网络特约商户
            'MerchantDetail' => base64_encode(json_encode([
                'ContactMobile'     => $mobile = '15802713829',
                // 联系人手机号。为商户常用联系人联系手机号。
                'ContactName'       => $contactName,
                // 联系人姓名。为商户常用联系人姓名。
                'PrincipalMobile'   => $mobile,
                // 负责人手机号。开户发送的短信验证码的手机号需要和负责人手机号一致。自然人和个体户必传，企业非必传
                'PrincipalCertType' => '01',
                // 负责人证件类型。01：身份证
                'PrincipalCertNo'   => '450101198408036368',
                // 负责人证件号码。备注：若自然人送自然人证件号码、若个体工商户送经营者证件号码、若企业送法人代表证件号码。
                'PrincipalPerson'   => $contactName
                // 负责人名称或企业法人代表姓名。备注：若商户类型为“自然人”填写责任人本人，若为“个体工商户”填写经营者本人，若为“企业”填写企业法人代表名称
            ])),
        ]);

        $client  = new Client();
        $headers = [
            'Content-Type' => 'application/xml',
        ];
        $request = new Request('POST', $this->baseRequestUrl, $headers, $xml);
        $res     = $client->sendAsync($request)->wait();

        $result = simplexml_load_string($res->getBody());

        $resultJson = json_decode(json_encode($result), 1);
        unset($resultJson['Signature']);
        return $resultJson;
    }

    public function preRegister01_2()
    {
        $this->baseRequestUrl = $this->bkServerUrl;
//        $this->baseRequestUrl = 'https://bkgw.mybank.cn/open/lite/api/common/request.htm';

        $this->baseFunction = 'ant.mybank.bkmerchantprod.merch.applet.pre.register';

        $xml = self::requestData([
            'IsvOrgId'       => $this->isvOrgId,
            'OutTradeNo'     => time(),
            'OutMerchantId'  => '001' . time(), // 商户号
            'MerchantType'   => '01', //商户类型。可选值：01：自然人02: 个体工商户03: 企业商户
//            'MerchantName'   => '夸父炸串测试商户',
            'MerchantName'   => $contactName = '傅架鼓',
            'DealType'       => '01', // 商户经营类型。可选值：01:实体特约商户02:网络特约商户03:实体兼网络特约商户
            'MerchantDetail' => base64_encode(json_encode([
                'ContactMobile'     => $mobile = '15802713829',
                // 联系人手机号。为商户常用联系人联系手机号。
                'ContactName'       => $contactName,
                // 联系人姓名。为商户常用联系人姓名。
                'PrincipalMobile'   => $mobile,
                // 负责人手机号。开户发送的短信验证码的手机号需要和负责人手机号一致。自然人和个体户必传，企业非必传
                'PrincipalCertType' => '01',
                // 负责人证件类型。01：身份证
                'PrincipalCertNo'   => '140102197805226834',
                // 负责人证件号码。备注：若自然人送自然人证件号码、若个体工商户送经营者证件号码、若企业送法人代表证件号码。
                'PrincipalPerson'   => $contactName
                // 负责人名称或企业法人代表姓名。备注：若商户类型为“自然人”填写责任人本人，若为“个体工商户”填写经营者本人，若为“企业”填写企业法人代表名称
            ])),
        ]);

        $client  = new Client();
        $headers = [
            'Content-Type' => 'application/xml',
        ];
        $request = new Request('POST', $this->baseRequestUrl, $headers, $xml);
        $res     = $client->sendAsync($request)->wait();

        $result = simplexml_load_string($res->getBody());

        $resultJson = json_decode(json_encode($result), 1);
        unset($resultJson['Signature']);
        return $resultJson;
    }

    public function merchUpdateMerchant()
    {
        $this->baseRequestUrl = $this->sbServerUrl;
        $this->baseFunction   = 'ant.mybank.merchantprod.merch.updateMerchant';

        $xml = self::requestData([
            'IsvOrgId'       => $this->isvOrgId,
            'MerchantId'     => $this->merchantNo,
            'MerchantDetail' => base64_encode(json_encode([
                'Address' => '黎里镇南京路 369 号 3 幢 121 号'
            ])),
            'OutTradeNo'     => time(),
        ]);

        return $this->baseRequest($xml);
    }

    public function merchantprodMerchQuery()
    {
        $this->baseRequestUrl = $this->sbServerUrl;
        $this->baseFunction   = 'ant.mybank.merchantprod.merch.query';

        $xml = self::requestData([
            'IsvOrgId'   => $this->isvOrgId,
            'MerchantId' => $this->merchantNo,
        ]);

        return $this->baseRequest($xml);
    }

    /**
     * @return mixed 02 个体工商户
     */
    public function preRegister02()
    {
//          "OutMerchantId" => "1671518499"
//  "IsvOrgId" => "202211000000000001902"
//  "OrderNo" => "2022122011150800120000000000000000704206"
        //       "MerchantId" => "226801000000761783643"
        $this->baseRequestUrl = $this->bkServerUrl;
        $this->baseFunction   = 'ant.mybank.bkmerchantprod.merch.applet.pre.register';

        $xml = self::requestData([
            'IsvOrgId'       => $this->isvOrgId,
            'OutTradeNo'     => time(),
            'OutMerchantId'  => time(), // 商户号
            'MerchantType'   => '02', //商户类型。可选值：01：自然人02: 个体工商户03: 企业商户
            'MerchantName'   => '床宿淆的店',
            'DealType'       => '01', // 商户经营类型。可选值：01:实体特约商户02:网络特约商户03:实体兼网络特约商户
            'MerchantDetail' => base64_encode(json_encode([
                'ContactMobile'     => $mobile = '14450763299',
                // 联系人手机号。为商户常用联系人联系手机号。
                'ContactName'       => $contactName = '床宿淆',
                // 联系人姓名。为商户常用联系人姓名。
                'PrincipalMobile'   => $mobile,
                // 负责人手机号。开户发送的短信验证码的手机号需要和负责人手机号一致。自然人和个体户必传，企业非必传
                'PrincipalCertType' => '01',
                // 负责人证件类型。01：身份证
                'PrincipalCertNo'   => '620103197908042449',
                // 负责人证件号码。备注：若自然人送自然人证件号码、若个体工商户送经营者证件号码、若企业送法人代表证件号码。
                'PrincipalPerson'   => $contactName,
                // 负责人名称或企业法人代表姓名。备注：若商户类型为“自然人”填写责任人本人，若为“个体工商户”填写经营者本人，若为“企业”填写企业法人代表名称
                'BussAuthType'      => '12',
                // 证件类型 若商户类型为“个体工商户”、“企业”需要填写证件类型 12：营业执照/统一社会信用代码 41：政府机关证件 42：部队证件 43：社会团体证件 44：事业单位证件 45：民办非企业组织证件 99：其它企业类型证件 备注： 个体工商户：选择12 企业：选择12
                'BussAuthNo'        => '9200097908042449XX',
                'BussAuthVld'       => "2099-12-30"
            ])),
        ]);

        return $this->baseRequest($xml);
    }

    /**
     * @return mixed 03 企业
     */
    public function preRegister03()
    {
        $this->baseRequestUrl = $this->bkServerUrl;
        $this->baseFunction   = 'ant.mybank.bkmerchantprod.merch.applet.pre.register';

        $xml = self::requestData([
            'IsvOrgId'       => $this->isvOrgId,
            'OutTradeNo'     => time(),
            'OutMerchantId'  => time(), // 商户号
            'MerchantType'   => '03', //商户类型。可选值：01：自然人02: 个体工商户03: 企业商户
            'MerchantName'   => '铬贫臻测试的公司',
            'DealType'       => '01', // 商户经营类型。可选值：01:实体特约商户02:网络特约商户03:实体兼网络特约商户
            'MerchantDetail' => base64_encode(json_encode([
                'ContactMobile'     => $mobile = '16210072227',
                // 联系人手机号。为商户常用联系人联系手机号。
                'ContactName'       => $contactName = '铬贫臻',
                // 联系人姓名。为商户常用联系人姓名。
                'PrincipalMobile'   => $mobile,
                // 负责人手机号。开户发送的短信验证码的手机号需要和负责人手机号一致。自然人和个体户必传，企业非必传
                'PrincipalCertType' => '01',
                // 负责人证件类型。01：身份证
                'PrincipalCertNo'   => '530104197810249454',
                // 负责人证件号码。备注：若自然人送自然人证件号码、若个体工商户送经营者证件号码、若企业送法人代表证件号码。
                'PrincipalPerson'   => $contactName,
                // 负责人名称或企业法人代表姓名。备注：若商户类型为“自然人”填写责任人本人，若为“个体工商户”填写经营者本人，若为“企业”填写企业法人代表名称
                'BussAuthType'      => '12',
                // 证件类型 若商户类型为“个体工商户”、“企业”需要填写证件类型 12：营业执照/统一社会信用代码 41：政府机关证件 42：部队证件 43：社会团体证件 44：事业单位证件 45：民办非企业组织证件 99：其它企业类型证件 备注： 个体工商户：选择12 企业：选择12
                'BussAuthNo'        => '9100097803301542XX',
                'BussAuthVld'       => "2099-12-30"
            ])),
        ]);

        $client  = new Client();
        $headers = [
            'Content-Type' => 'application/xml',
        ];
        $request = new Request('POST', $this->baseRequestUrl, $headers, $xml);
        $res     = $client->sendAsync($request)->wait();

        $result = simplexml_load_string($res->getBody());

        $resultJson = json_decode(json_encode($result), 1);
        unset($resultJson['Signature']);
        return $resultJson;
    }

    /**
     * @return mixed 入驻激活查询
     */
    public function appletRegisterRuery()
    {
        $this->baseRequestUrl = $this->bkServerUrl;
        $this->baseFunction   = 'ant.mybank.merchantprod.merch.applet.register.query';

        $xml = self::requestData(
            [
                'IsvOrgId'      => $this->isvOrgId,
                'OutMerchantId' => $this->outMchId,
            ]);

        return $this->baseRequest($xml);
    }

    /**
     * 入驻查询
     *
     * @return mixed
     */
    public function registerQuery()
    {
        $this->baseRequestUrl = $this->sbServerUrl;
        $this->baseFunction   = 'ant.mybank.merchantprod.merch.register.query';

        $xml = self::requestData([
            'IsvOrgId' => $this->isvOrgId,
            'OrderNo'  => $this->orderNo,
        ]);

        $client  = new Client(['verify' => false]);
        $headers = [
            'Content-Type' => 'application/xml',
        ];

        $request = new Request('POST', $this->baseRequestUrl, $headers, $xml);
        $res     = $client->sendAsync($request)->wait();

        $result = simplexml_load_string($res->getBody());

        $resultJson = json_decode(json_encode($result), 1);
        unset($resultJson['Signature']);
        return $resultJson;
    }

    /**
     * 图片上传
     *
     * @return mixed
     */
    public function uploadFile()
    {
        $outTradeNo = time();
        $client     = new Client();
        $body       = [
            'IsvOrgId'   => $this->isvOrgId,
            'PhotoType'  => '01',
            // 图片类型。可选值：01 身份证正面,02 身份证反面,03 营业执照,04组织机构代码证,05 开户许可证,06 门头照,07 其他,08 收银台照片,09 门店内景照片
            'OutTradeNo' => $outTradeNo,
            'Function'   => 'ant.mybank.merchantprod.merchant.uploadphoto',
            'Version'    => '1.0.0',
            'AppId'      => $this->appId,
            'ReqTime'    => date('YmdHis')
        ];

        ksort($body);
        $bodyStr    = http_build_query($body);
        $bodyStr    = urlencode($bodyStr);
        $privateKey = openssl_pkey_get_private($this->privatekey);
        openssl_sign($bodyStr, $signature, $privateKey, OPENSSL_ALGO_SHA256);
        $sign              = base64_encode($signature);
        $body['Signature'] = $sign;


        $multipart = [];
        foreach ($body as $bodyKey => $bodyVaule) {
            $multipart[] = [
                'name'     => $bodyKey,
                'contents' => $bodyVaule
            ];
        }

//        dd($body);

        $filename    = '/www/rms-api/tmp/zheng.png';
        $multipart[] = [
            'name'     => 'Picture',
            'contents' => Utils::tryFopen($filename, 'r'),
            'filename' => $filename
        ];

//        dd($multipart);


        $options = [
            'multipart' => $multipart
        ];

        $request    = new Request('POST',
            'http://bkgwdev.dl.alipaydev.com/ant/mybank/merchantprod/merchant/uploadphoto.htm');
        $res        = $client->sendAsync($request, $options)->wait();
        $result     = simplexml_load_string($res->getBody());
        $resultJson = json_decode(json_encode($result), 1);
        unset($resultJson['Signature']);
        return $resultJson;
    }

}